package orm;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.HashMap;

import com.u2b.db.datasource.DbcpHandler;
import com.u2b.exceptions.DaoException;
import com.u2b.global.utils.CheckParameter;
import com.u2b.servlet.utils.ParameterParser;

public class UpdateProxy
{
    private Connection conn;
    private PreparedStatement ps;

    public UpdateProxy()
    {
        try
        {
            conn = DbcpHandler.getInstance().getWriteConnection();
        }
        catch (Exception e)
        {
            throw new RuntimeException(this.getClass().getName(), e);
        }
        System.out.println(this.getClass().getName() + ".......connection......" + conn);

    }

    public int update(String sql, String[] sqlKeys, HashMap<String, Object> value)
    {
        Object[] SQLvalues = new ParameterParser().getSQLValuesFromMap(sqlKeys, value);
        int flag = 0;
        try
        {
            PreparedStatement ps = conn.prepareStatement(sql);
            CheckParameter.checkParameterNumber(SQLvalues.length, ps);
            for (int i = 0; i < SQLvalues.length; i++)
            {
                ps.setObject(i + 1, SQLvalues[i]);
                System.out.println(this.getClass().getName() + "......." + SQLvalues[i] + ".......");
            }
            flag = ps.executeUpdate();
        }
        catch (SQLException e)
        {

            throw new DaoException(this.getClass().getName() + "........" + e.getMessage(), e);
        }
        finally
        {
            // instance.free(conn, ps, null);
        }
        return flag;
    }

    public int update(String sql)
    {
        int flag = 0;
        try
        {
            ps = conn.prepareStatement(sql);
            flag = ps.executeUpdate();

        }
        catch (SQLException e)
        {
            throw new DaoException(this.getClass().getName() + "........" + e.getMessage(), e);
        }
        finally
        {
            // instance.free(conn, ps, null);
        }
        return flag;

    }
}
